<template>
  <div class="inquiry-price-page">
    <!-- 筛选区域 -->
    <div class="filter-section">
      <el-form :inline="true" :model="filterForm" ref="filterForm">
        <el-form-item label="交易角色">
          <el-select v-model="filterForm.tradeRole" placeholder="全部">
            <el-option value="" label="全部"></el-option>
            <el-option value="卖方" label="卖方"></el-option>
            <el-option value="买方" label="买方"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="资产类型">
          <el-select
            v-model="filterForm.assetType"
            placeholder="全部"
            v-loading="assetTypeLoading"
          >
            <el-option value="" label="全部"></el-option>
            <!-- 动态渲染选项 -->
            <el-option
              v-for="item in assetTypeOptions"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="询价截止日期">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>

        <el-form-item label="卖方机构搜索">
          <el-input
            v-model="filterForm.sellerName"
            placeholder="输入卖方机构名称"
          ></el-input>
        </el-form-item>

        <el-form-item label="买方机构搜索">
          <el-input
            v-model="filterForm.buyerName"
            placeholder="输入买方机构名称"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <el-table
      :data="tableData"
      stripe
      v-loading="tableLoading"
      element-loading-text="正在加载数据..."
    >
      <el-table-column prop="id" label="编号" width="80"></el-table-column>
      <el-table-column prop="dialogue" label="对话" width="120">
        <template slot-scope="scope">
          {{ scope.row.dialogue }}
        </template>
      </el-table-column>
      <el-table-column prop="tradeRole" label="交易角色" width="120">
        <template slot-scope="scope">
          {{ scope.row.tradeRole === "0270000001" ? "买方" : "卖方" }}
        </template>
      </el-table-column>
      <el-table-column
        prop="assetType"
        label="资产类型"
        width="120"
      ></el-table-column>
      <el-table-column
        prop="projectType"
        label="项目类型"
        width="120"
      ></el-table-column>
      <el-table-column
        prop="sellerTradeQuantity"
        label="报价量(tCO2e)"
        width="140"
      ></el-table-column>
      <el-table-column
        prop="sellerUnitPrice"
        label="报价(元/tCO2e)"
        width="140"
      >
        <template slot-scope="scope">
          {{ scope.row.sellerUnitPrice || "--" }}
        </template>
      </el-table-column>
      <el-table-column
        prop="buyerTradeQuantity"
        label="询价量(tCO2e)"
        width="140"
      ></el-table-column>
      <el-table-column prop="buyerUnitPrice" label="询价(元/tCO2e)" width="140">
        <template slot-scope="scope">
          {{ scope.row.buyerUnitPrice || "--" }}
        </template>
      </el-table-column>
      <el-table-column
        prop="expirationDate"
        label="截止日期"
        width="140"
      ></el-table-column>
      <el-table-column
        prop="sellerDeliveryMethod"
        label="拟交割方式"
        width="140"
      >
        <template slot-scope="scope">
          {{ scope.row.sellerDeliveryMethod || "--" }}
        </template>
      </el-table-column>
      <el-table-column prop="sellerDeliveryTime" label="拟交割时间" width="140">
        <template slot-scope="scope">
          {{ scope.row.sellerDeliveryTime || "--" }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template slot-scope="scope">
          <el-button type="text" @click="handleEdit(scope.row)"
            >询报价</el-button
          >
          <el-button type="text" @click="handleIntention(scope.row)"
            >意向成交</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount"
      ></el-pagination>
    </div>

    <!-- 意向成交弹窗 -->
    <el-dialog
      :title="intentionTitle"
      :visible.sync="intentionVisible"
      width="600px"
    >
      <el-form ref="intentionForm" :model="intentionForm" label-width="150px">
        <el-form-item label="供应方机构名称">
          <el-input v-model="intentionForm.sellerName" disabled></el-input>
        </el-form-item>
        <el-form-item label="采购方机构名称">
          <el-input v-model="intentionForm.buyerName" disabled></el-input>
        </el-form-item>
        <el-form-item label="供应方联系电话">
          <el-input v-model="intentionForm.sellerPhone"></el-input>
        </el-form-item>
        <el-form-item label="采购方联系电话">
          <el-input v-model="intentionForm.buyerPhone"></el-input>
        </el-form-item>
        <el-form-item label="资产类型">
          <el-input v-model="intentionForm.assetType" disabled></el-input>
        </el-form-item>
        <el-form-item label="项目类型">
          <el-input v-model="intentionForm.projectType" disabled></el-input>
        </el-form-item>
        <el-form-item label="交易量(tCO2e)">
          <el-input v-model="intentionForm.tradeQuantity"></el-input>
        </el-form-item>
        <el-form-item label="资产单价(元/tCO2e)">
          <el-input v-model="intentionForm.assetUnitPrice"></el-input>
        </el-form-item>
        <el-form-item label="交割时间">
          <el-input v-model="intentionForm.deliveryTime"></el-input>
        </el-form-item>
        <el-form-item label="交割方式">
          <el-input v-model="intentionForm.deliveryMethod"></el-input>
        </el-form-item>
        <el-form-item label="交割交易所">
          <el-input v-model="intentionForm.deliveryExchange"></el-input>
        </el-form-item>
        <el-form-item label="截止日期">
          <el-input v-model="intentionForm.expirationDate" disabled></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="intentionForm.remark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="intentionVisible = false">取消</el-button>
        <el-button type="primary" @click="submitIntention">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { MessageBox } from "element-ui";
export default {
  name: "InquiryPricePage",
  data() {
    return {
      user: JSON.parse(localStorage.getItem("user") || "{}"),
      assetTypeOptions: [], // 用于存储initTypeOptions获取的选项
      assetTypeLoading: false,
      // 筛选表单
      filterForm: {
        tradeRole: "",
        assetType: "",
        projectType: "",
        dateRange: [],
        sellerName: "",
        buyerName: "",
        tenantId: "",
      },
      // 表格数据
      tableData: [],
      tableLoading: false,
      totalCount: 0,
      currentPage: 1,
      pageSize: 10,

      // 分页相关
      pageSizes: [10, 20, 50],

      // 意向成交弹窗
      intentionVisible: false,
      intentionTitle: "意向成交",
      intentionForm: {
        id:"",
        sellerId:"",
        buyerId:"",
        sellerName: "",
        buyerName: "",
        sellerPhone: "",
        buyerPhone: "",
        assetType: "",
        projectType: "",
        tradeQuantity: "",
        assetUnitPrice: "",
        deliveryTime: "",
        deliveryMethod: "",
        deliveryExchange: "",
        expirationDate: "",
        remark: "",
      },
    };
  },
  created() {
    this.fetchTableData();
  },
  mounted() {
    // this.initDeliveryOptions(); // 新增获取交割方式数据的调用
    this.initTypeOptions();
  },
  methods: {
    handleIntention(row) {
  this.intentionVisible = true;

  // 从表格行数据中自动带出已有字段值
  this.intentionForm = {
    sellerName: row.sellerName || "",
    buyerName: row.buyerName || "",
    sellerId: row.sellerId||"",
    buyerId: row.buyerId||"",
    sellerPhone: row.sellerPhone,
    buyerPhone: row.buyerPhone ,
    assetType: row.assetType || "",
    projectType: row.projectType || "",
    tradeQuantity: row.sellerTradeQuantity  || "",
    assetUnitPrice: row.sellerUnitPrice ||  "",
    deliveryTime: row.sellerDeliveryTime || "",
    deliveryMethod: row.sellerDeliveryMethod || "",
    deliveryExchange: row.sellerDeliveryExchange || "",
    expirationDate: row.expirationDate || "",
    remark: "",
    id: row.id,
  };
},
submitIntention() {
  this.$refs.intentionForm.validate((valid) => {
    if (valid) {
      this.$request.post('/trade/carbonTradeContract/submitIntention', this.intentionForm)
        .then(res => {
          if (res.code === 200) {
            // 先弹出提示弹窗
            MessageBox({
              title: '提示',
              message: '您的意向单已提交，为您跳转到交易所完成后续履约',
              type: 'info',
              showCancelButton: false, // 不显示取消按钮
              confirmButtonText: '确定',
              callback: (action) => {
                if (action === 'confirm') { 
                  window.location.href = 'https://www.cneeex.com'; 
                }
              }
            });
            this.intentionVisible = false;
            this.fetchTableData();
          } else {
            this.$message.error(res.msg || '提交失败');
          }
        })
        .catch(() => {
          this.$message.error('网络错误，请重试');
        });
    }
  });
},
    async fetchDeliveryOptions(type) {
      this.assetTypeLoading = true;
      try {
        // 调用后端接口，传递type参数（路径参数）
        const res = await this.$request.get(
          `/trade/carbonTradeQuote/getDeliveryMethod/${type}`
        );
        // 假设后端返回格式：{ success: true, data: [] }（根据你的ApiResult结构调整）
        if (res.code == 200) {
          return res.data; // 返回查询到的列表
        } else {
          this.$message.warning("获取数据失败");
          return [];
        }
      } catch (error) {
        console.error(`获取${type}失败：`, error);
        return [];
      } finally {
        this.assetTypeLoading = false;
      }
    },
    async initTypeOptions() {
      // 2. 获取资产类型（type=assetType）
      const places = await this.fetchDeliveryOptions("assetType");
      this.assetTypeOptions = places;
    },
    // 获取表格数据
    async fetchTableData() {
      this.tableLoading = true;
      try {
        this.filterForm.tenantId = this.user.tenantId;
        // 模拟接口请求，实际替换为真实接口
        const res = await this.$request.post(
          "/trade/carbonTradePrice/handleSearch",
          {
            currentPage: this.currentPage,
            pageSize: this.pageSize,
            ...this.filterForm, // 展开筛选条件，合并为一个 JSON 对象
          }
        );
        if (res.code === 200) {
          this.tableData = res.data.list;
          this.totalCount = res.data.total;
        }
      } catch (error) {
        console.error("获取数据失败:", error);
        this.$message.error("网络错误，请重试");
      } finally {
        this.tableLoading = false;
      }
    },
    // 搜索
    handleSearch() {
      this.currentPage = 1;
      this.fetchTableData();
    },
    // 重置筛选
    resetFilter() {
      this.filterForm = {
        tradeRole: "",
        assetType: "",
        projectType: "",
        dateRange: [],
        sellerName: "",
        buyerName: "",
      };
      this.fetchTableData();
    },
    // 每页条数改变
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchTableData();
    },
    // 当前页改变
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchTableData();
    },
    // 编辑报价
    // 询报价按钮点击事件
    //   handleEdit(row) {
    //     MessageBox.alert("与对方交谈成功", "提示", {
    //       confirmButtonText: "确定",
    //       type: "success",
    //     }).then(() => {
    //       console.log("用户确认了交谈成功提示");
    //     }).finally(() => {
    //   if (buttonEl && buttonEl.blur) {
    //     buttonEl.blur();
    //   }
    // });
    //   },
    handleEdit(row) {
      // 记录当前点击的按钮
      const button = document.activeElement;

      // 弹出提示弹窗
      MessageBox.alert("与对方协商成功", "提示", {
        confirmButtonText: "确定",
        type: "success",
        // 增加关闭前的回调
        beforeClose: (action, instance, done) => {
          done(); // 关闭弹窗
          // 延迟执行，确保弹窗已完全关闭
          setTimeout(() => {
            if (button && button.blur) {
              button.blur();
            }
            // 额外措施：将焦点移到文档其他地方
            document.body.focus();
          }, 100);
        },
      }).then(() => {
        console.log("用户确认了交谈成功提示");
      });
    },
    
  },
};
</script>

<style scoped>
.inquiry-price-page {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 40px);
}

.filter-section {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

::v-deep .el-table th {
  background-color: #f5f7fa;
  font-weight: 500;
}

::v-deep .el-table td,
::v-deep .el-table th {
  text-align: center;
}

.dialog-footer {
  text-align: right;
}

/* 响应式 */
@media screen and (max-width: 1200px) {
  .filter-section {
    overflow-x: auto;
    padding-bottom: 15px;
  }
}
</style>